import configStore from '@/stores/configStore'
import publicStore from '@/stores/publicStore'
import router from '@/router'
import api from '@/api'

// 权限
export function isAuth() {
    let auth: any = router.currentRoute.value.meta.auth
    if (auth && auth.length != 0 && configStore().token) {
        let time = new Date().getTime() - parseInt(configStore().token)
        if (time >= 60 * 60 * 1000) {
            configStore().token = ''
            configStore().user = ''
            router.push({path: '/home'})
        } else {
            configStore().token = new Date().getTime() + ''
        }
    } else {
        if (configStore().token) {
            let time = new Date().getTime() - parseInt(configStore().token)
            if (time >= 60 * 60 * 1000) {
                configStore().token = ''
                configStore().user = ''
            }
        }
    }
}

// 请求ip
export function getIp() {
    let ip = configStore().ip.trim()
    if (ip.indexOf('http') == -1) {
        ip = 'http://' + ip
    }
    return ip
}

// 请求地址
export function getHttp(type: any = '') {
    isAuth()
    // 绑定ip和端口
    if (type == 'ip' || type == 'prot') {
        console.log('获取IP，端口', type)
        let req = import.meta.env.MODE != 'development' ? window.location.origin : import.meta.env.VITE_BASE_URL
        req = req.replace('http://', "")
        let i = req.indexOf(':')
        if (type == 'ip') return req.substring(0, i)
        if (type == 'prot') return req.substring(i + 1, req.length)
    } else {
        // 临时动态ip
        if (type.headers && type.headers.ip) return type.headers.ip.indexOf('http') == -1 ? 'http://' + type.headers.ip : type.headers.ip
        // 切换动态ip
        let ip = configStore().ip.trim()
        if (ip) return ip.indexOf('http') == -1 ? 'http://' + ip : ip
        // 生产环境ip
        if (import.meta.env.MODE != 'development') return window.location.origin
        // 开发环境ip
        return ''
    }
}

// 公用属性
export function setPublic(obj: any) {
    publicStore()._public = Object.assign(publicStore()._public, obj)
}

// 跳转页面
export function toPath(path: any, query: any, type: any) {
    if (type == 1) {
        window.location.href = path
    } else {
        if (query) {
            router.push({path: path, query: query})
        } else {
            router.push({path: path})
        }
    }
}

// 判断空
export function isNull(val: any) {
    let valString = typeof (val) == 'object' ? JSON.stringify(val) : val + ""
    let verificationType = ["", "null", "undefined", "{}", "[]"]
    return verificationType.includes(valString)
}

// 对象转换
export function varObj(name: any, val: any) {
    var objName = name
    var objValue = val
    var obj: any = {}
    obj[objName] = objValue
    return obj
}

// 数组条件取值
export function find(array: any, condition: any, name: any) {
    let value = array.find((a: any) => {
        return a[condition[0]] == condition[1]
    })
    return value != undefined ? name != undefined ? value[name] : value : ""
}

// 数组条件取下标
export const findIndex = (array: any, condition: any) => {
    let index = array.findIndex((a: any) => {
        return a[condition[0]] == condition[1]
    })
    return index != -1 ? index : ""
}

// 数组去重
export function findReduct(array: any, condition: any) {
    let obj: any = {};
    let arr = array.reduce((cur: any, item: any) => {
        obj[item[condition]] ? "" : obj[item[condition]] = true && cur.push(item)
        return cur;
    }, [])
    return arr
}

// 两数组并集
export function findUnion(array: any, array2: any, condition: any) {
    let arr = Array.from(new Set([...array, ...array2]))
    return findReduct(arr, condition)
}

// 两数组交集
export function findInter(array: any, array2: any, condition: any, condition2: any) {
    let arr = [...array].filter(x => [...array2].some(y => y[condition] === x[condition2 ? condition2 : condition]));
    return arr
}

// 两数组补集
export function findDiffer(array: any, array2: any, condition: any, condition2: any) {
    let arr = [...array].filter(x => [...array2].every(y => y[condition] !== x[condition2 ? condition2 : condition]));
    return arr
}

// 导出功能
// export function handleExport(data:any, content:any) {
//   const url:any = '@/utils/Export2Excel'
//   import(url).then(excel => {
//     const tHeader:any  = []
//     const filterVal = []
//     content.forEach((item:any) => {
//       if(item.show){
//         tHeader.push(item.name)
//         filterVal.push(item.key)
//       }
//     })
//     excel.export_json_to_excel({
//       header: tHeader,
//       data,
//       filename: '导出'
//     })
//   })
// }
// 当前时间
export function clock() {
    const date = new Date()
    const year = date.getFullYear()
    const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    const hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
    const seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
    // let week = date.getDay() // 星期
    // let weekArr = [ '星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六' ]
    const time = {ymd: year + '-' + month + '-' + day, sfm: hours + ':' + minutes + ':' + seconds}
    return time
}

// 日期格式化
export function parseTime(time: any, pattern: any) {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
            time = parseInt(time)
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj: any = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result: any, key: any) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}

// 替换对象字段名称
export function renameProperty(obj: any, oldName: any, newName: any) {
    let rest
    // 检查对象中是否有旧属性名
    if (obj.hasOwnProperty(oldName)) {
        // 使用解构语法将旧属性名重命名为新属性名
        ({[oldName]: obj[newName], ...rest} = obj);
        // 将对象的属性重新组装
        obj = {[newName]: obj[newName], ...rest};
    }
    return obj;
}

// 判断对象是否相同
export function deepObjectEquals(obj1: any, obj2: any) {
    if (Object.keys(obj1).length !== Object.keys(obj2).length) {
        return false;
    }
    for (let key in obj1) {
        if (typeof obj1[key] === "object" && typeof obj2[key] === "object") {
            if (!deepObjectEquals(obj1[key], obj2[key])) {
                return false;
            }
        } else if (obj1[key] !== obj2[key]) {
            return false;
        }
    }
    return true;
}

// 判断数组是否相同
export function deepArrayEquals(arr1: any, arr2: any) {
    if (arr1.length !== arr2.length) {
        return false;
    }
    for (let i = 0; i < arr1.length; i++) {
        if (Array.isArray(arr1[i]) && Array.isArray(arr2[i])) {
            if (!deepArrayEquals(arr1[i], arr2[i])) {
                return false;
            }
        } else if (arr1[i] !== arr2[i]) {
            return false;
        }
    }
    return true;
}

// 判断json
export function isJSON(str: any) {
    if (typeof str != 'string') {
        console.log('It is not a string! [' + str + ']')
        return false;
    }
    try {
        var obj = JSON.parse(str);
        if (typeof obj == 'object' && obj) {
            console.log('转换成功：' + str);
            return true;
        } else {
            console.log('转换失败：' + str);
            return false;
        }
    } catch (e) {
        console.log('error：[' + str + '] !!! ' + e);
        return false;
    }
    return false;
}

// 判断数组
export function isArray(str: any) {
    if (str.constructor === Array) {
        return true
    } else {
        return false
    }
}

// 判断对象
export function isObject(str: any) {
    if (str.constructor === Object) {
        return true
    } else {
        return false
    }
}

// 更新
export async function update(form: any) {
    let result: any = '';
    await api.updateApi(form).then((res: any) => {
        if (res.errcode == 0) {
            result = true
        }
    }).catch((err: any) => {
        console.log('err', err)
        result = false
    })
    return result
}

export const install = (app: any) => {
    app.config.globalProperties.toPath = toPath;
    app.config.globalProperties.isNull = isNull;
    app.config.globalProperties.varObj = varObj;
    app.config.globalProperties.find = find;
    app.config.globalProperties.findIndex = findIndex;
    app.config.globalProperties.findReduct = findReduct;
    app.config.globalProperties.findInter = findInter;
    app.config.globalProperties.findDiffer = findDiffer;
    // app.config.globalProperties.handleExport = handleExport;
    app.config.globalProperties.clock = clock;
    app.config.globalProperties.parseTime = parseTime;
    app.config.globalProperties.renameProperty = renameProperty
    app.config.globalProperties.isJSON = isJSON;
    app.config.globalProperties.isArray = isArray;
    app.config.globalProperties.isObject = isObject;
    app.config.globalProperties.isAuth = isAuth;
    app.config.globalProperties.getIp = getIp;
    app.config.globalProperties.getHttp = getHttp;
    app.config.globalProperties.setPublic = setPublic;
    app.config.globalProperties.update = update;
}

